/*
* 受限空间作业详情（审批）
* */

import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:center_beijing/api/product_api.dart';
import 'package:center_beijing/api/task_api.dart';
import 'package:center_beijing/common/notification.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/common/utils.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/config/routeConfig.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart' as Go;
import 'package:dio/dio.dart' as ImageForm;
import 'package:images_picker/images_picker.dart';
import 'package:http_parser/http_parser.dart';

class ConfinedSpaceDetail extends StatefulWidget {
  const ConfinedSpaceDetail();

  @override
  _ConfinedSpaceDetailState createState() => _ConfinedSpaceDetailState();
}

class _ConfinedSpaceDetailState extends State<ConfinedSpaceDetail> {
  CustomLoading loading = CustomLoading.withMessage('提交中...');
  var ids = Go.Get.arguments;
  var detail = Map();
  List dangerList = []; //危险因素所有对象列表
  List<String> dangerSelectList = []; //危险因素显示
  List<bool> dangerSelectedList = []; //危险因素是否被选中
  List workList = []; //安全措施
  List personSafeListAll = []; //个人防护器材所有对象列表
  List gasList = []; //气体检测检查项
  List signRecords = []; //流程签名列表

  List<Media> photos = [];
  ImageForm.FormData formData;
  List passPhoto = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.getDetail();
  }

  /*
  * 获取详情
  * */
  getDetail() async {
    var result = await getConfinedSpaceWorkEx({
      'id': ids['businessId'],
    });
    if (result != null && result.length > 0) {
      List bbq = result['dangerFactors'].map((item) {
        dangerSelectedList.add(item['checkedTag'] == '1');
        return item['dangerName'].toString();
      }).toList();
      this.setState(() {
        detail = result;
        dangerList = result['dangerFactors'];
        dangerSelectList = bbq.cast();
        workList = result['safeStepRecords'];
        personSafeListAll = result['equipRecords'];
        gasList = result['gasRecords'];
        signRecords = result['signRecords'];
      });
    }
  }

  Future addImage() async {
    this.passPhoto = [];
    var tem = [];
    loading.show(delay: 30);
    for (var l = 0; l < workList.length; l++) {
      if (workList[l]['paint'] != null) {
        tem.add(l);
        passPhoto.add(workList[l]);
      }
    }
    if (this.passPhoto.length > 0) {
      formData = new ImageForm.FormData.fromMap({
        "tenantId": GlobalConfig.tenantId,
      });
      for (int i = 0; i < passPhoto.length; i++) {
        formData.files.add(MapEntry(
            "files",
            await ImageForm.MultipartFile.fromBytes(passPhoto[i]['paint'],
                filename: "bbq.jpg", contentType: MediaType('image', 'png'))));
      }
      var result = await uploadImage(formData, GlobalConfig.tenantId);
      if (result != null && result.length > 0) {
        for (var i = 0; i < result.length; i++) {
          workList[tem[i]]['tutelageSignId'] = result[i]['attachmentId'];
        }
      }
    }
    this.submit();
  }

  submit() async {
    var pass = {
      'spaceWorkId': ids['businessId'],
      'taskId': ids['taskId'],
      'signContent': '',
      'signResult': '1',
      'signTime': Utils.timeUtil(DateTime.now().toIso8601String()),
      'taskKey': ids['taskKey'],
      'safeStepRecords': jsonEncode(workList
          .map((e) => {
        'id': e['id'],
        'tutelageSignId': e['tutelageSignId'] ?? '',
      })
          .toList())
    };
    var result = await saveConfinedSpaceWorkProcess(pass);
    loading.dismiss();
    if (result != null) {
      Fluttertoast.showToast(msg: '提交成功');
      Go.Get.back(result: '成功');
      bus.emit('refreshHome');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('受限空间作业'),
        ),
        body: SafeArea(
          child: Container(
            padding: EdgeInsets.only(
                bottom: MediaQuery.of(context).padding.bottom + 40),
            child: SingleChildScrollView(
              child: Column(
                children: [
                  Container(
                    padding: EdgeInsets.fromLTRB(
                        Styles.spacing8, 0, Styles.spacing8, 0),
                    color: Colors.white,
                    child: Column(
                      children: [
                        Container(
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing8,
                              Styles.spacing16,
                              Styles.spacing8,
                              Styles.spacing16),
                          alignment: Alignment.centerLeft,
                          child: Text(
                            '基本信息',
                            style: TextStyle(
                                color: Styles.BlackColor,
                                fontSize: Styles.MainButtonTextFont,
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                        Container(
                          decoration: BoxDecoration(
                              border: Border(
                                  bottom: BorderSide(
                                      color: Styles.LightSearch, width: 1))),
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing8,
                              Styles.spacing16,
                              Styles.spacing8,
                              Styles.spacing16),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '作业名称',
                                style: TextStyle(
                                    color: Styles.TitleColor,
                                    fontSize: Styles.Middle15Font),
                              ),
                              Text(
                                detail['workName'] ?? '--',
                                style: TextStyle(
                                    color: Styles.TitleColor,
                                    fontSize: Styles.Middle15Font),
                              )
                            ],
                          ),
                        ),
                        Container(
                          decoration: BoxDecoration(
                              border: Border(
                                  bottom: BorderSide(
                                      color: Styles.LightSearch, width: 1))),
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing8,
                              Styles.spacing16,
                              Styles.spacing8,
                              Styles.spacing16),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '作业时间',
                                style: TextStyle(
                                    color: Styles.TitleColor,
                                    fontSize: Styles.Middle15Font),
                              ),
                              Text(
                                detail['workTimeStr'] ?? '--',
                                style: TextStyle(
                                    color: Styles.TitleColor,
                                    fontSize: Styles.Middle15Font),
                              )
                            ],
                          ),
                        ),
                        Container(
                          decoration: BoxDecoration(
                              border: Border(
                                  bottom: BorderSide(
                                      color: Styles.LightSearch, width: 1))),
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing8,
                              Styles.spacing16,
                              Styles.spacing8,
                              Styles.spacing16),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '作业班组',
                                style: TextStyle(
                                    color: Styles.TitleColor,
                                    fontSize: Styles.Middle15Font),
                              ),
                              Text(
                                detail['teamName'] ?? '--',
                                style: TextStyle(
                                    color: Styles.TitleColor,
                                    fontSize: Styles.Middle15Font),
                              )
                            ],
                          ),
                        ),
                        Container(
                          decoration: BoxDecoration(
                              border: Border(
                                  bottom: BorderSide(
                                      color: Styles.LightSearch, width: 1))),
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing8,
                              Styles.spacing16,
                              Styles.spacing8,
                              Styles.spacing16),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '所属部门',
                                style: TextStyle(
                                    color: Styles.TitleColor,
                                    fontSize: Styles.Middle15Font),
                              ),
                              Text(
                                detail['deptName'] ?? '--',
                                style: TextStyle(
                                    color: Styles.TitleColor,
                                    fontSize: Styles.Middle15Font),
                              )
                            ],
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing8,
                              Styles.spacing16,
                              Styles.spacing8,
                              Styles.spacing4),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '施工内容',
                                style: TextStyle(
                                    color: Styles.TitleColor,
                                    fontSize: Styles.Middle15Font),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          alignment: Alignment.centerLeft,
                          decoration: BoxDecoration(
                              border: Border(
                                  bottom: BorderSide(
                                      color: Styles.LightSearch, width: 1))),
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing8,
                              Styles.spacing4,
                              Styles.spacing8,
                              Styles.spacing16),
                          child: Text(
                            detail['workContent'] ?? '--',
                            style: TextStyle(
                                color: Styles.TitleColor,
                                fontSize: Styles.Middle15Font),
                          ),
                        ),
                        Container(
                          alignment: Alignment.centerLeft,
                          margin: EdgeInsets.fromLTRB(
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16),
                          child: Text(
                            '危险因素',
                            style: TextStyle(
                                color: Styles.TitleColor,
                                fontSize: Styles.Middle15Font),
                          ),
                        ),
                        Container(
                          alignment: Alignment.centerLeft,
                          child: Wrap(
                            children: dangerList.map((e) {
                              return e['checkedTag'] == '1'
                                  ? Container(
                                      margin: EdgeInsets.fromLTRB(
                                          Styles.spacing8,
                                          0,
                                          0,
                                          Styles.spacing8),
                                      padding: EdgeInsets.fromLTRB(
                                          Styles.spacing8,
                                          Styles.spacing4,
                                          Styles.spacing8,
                                          Styles.spacing4),
                                      decoration: BoxDecoration(
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(12.r)),
                                          color: Styles.LightBlueColor2),
                                      child: Text(
                                        e['dangerName']??'',
                                        style: TextStyle(
                                            color: Colors.white,
                                            fontSize: Styles.NormalFont13),
                                      ),
                                    )
                                  : SizedBox();
                            }).toList(),
                          ),
                        )
                      ],
                    ),
                  ),
                  Container(
                    color: Colors.white,
                    padding: EdgeInsets.fromLTRB(
                        Styles.spacing8, 0, Styles.spacing8, 0),
                    margin: EdgeInsets.only(top: Styles.spacing16),
                    child: Column(
                      children: [
                        Container(
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing8,
                              Styles.spacing16,
                              Styles.spacing8,
                              Styles.spacing16),
                          alignment: Alignment.centerLeft,
                          child: Text(
                            '主要安全措施',
                            style: TextStyle(
                                color: Styles.BlackColor,
                                fontSize: Styles.MainButtonTextFont,
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                        ListView.builder(
                          physics: const NeverScrollableScrollPhysics(),
                          shrinkWrap: true,
                          itemCount: workList.length,
                          itemBuilder: (BuildContext context, int index) {
                            //条目构建函数传入了index,根据index索引到特定图片
                            return Container(
                              decoration: BoxDecoration(
                                  border: Border(
                                      bottom: BorderSide(
                                          color: Styles.SpatLineColor,
                                          width: 1))),
                              padding: EdgeInsets.fromLTRB(Styles.spacing8,
                                  Styles.spacing16, Styles.spacing8, 0),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text.rich(TextSpan(children: [
                                    TextSpan(
                                        text: "${(index + 1).toString()}、",
                                        style: TextStyle(
                                            color: Styles.BlackColor,
                                            fontSize: Styles.Middle15Font)),
                                    TextSpan(
                                        text:
                                            "${workList[index]['safeStepContent']}",
                                        style: TextStyle(
                                            color: Styles.BlackColor,
                                            fontSize: Styles.Middle15Font)),
                                  ])),
                                  Container(
                                    margin: EdgeInsets.fromLTRB(
                                        0,
                                        Styles.spacing16,
                                        Styles.spacing16,
                                        Styles.spacing16),
                                    alignment: Alignment.centerLeft,
                                    color: Colors.white,
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text.rich(TextSpan(children: [
                                          TextSpan(
                                              text: '作业人',
                                              style: TextStyle(
                                                  fontSize: Styles.Middle15Font,
                                                  color: Styles.TitleColor)),
                                        ])),
                                        (workList[index]['workSignId'] !=
                                                    null &&
                                                workList[index]['workSignId'] !=
                                                    '')
                                            ? Image.network(
                                                "${GlobalConfig.baseUrl}fs/irest/file/mps_fileTransferHandler/image?id=${workList[index]['workSignId']}&ZJQFSESSION=${GlobalConfig.session}",
                                                width: 80.w,
                                                height: 30.h,
                                              )
                                            : Container()
                                      ],
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.fromLTRB(
                                        0,
                                        Styles.spacing8,
                                        Styles.spacing16,
                                        Styles.spacing16),
                                    alignment: Alignment.centerLeft,
                                    color: Colors.white,
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text.rich(TextSpan(children: [
                                          TextSpan(
                                              text: '监护人',
                                              style: TextStyle(
                                                  fontSize: Styles.Middle15Font,
                                                  color: Styles.TitleColor)),
                                        ])),
                                        GestureDetector(
                                          onTap: () async {
                                            print('签名');
                                            var result = await Go.Get.toNamed(
                                                RouteConfig.sign);
                                            if (result != null) {
                                              workList[index]['paint'] = result;
                                            }
                                            this.setState(() {});
                                          },
                                          child: Container(
                                            child: workList[index]['paint'] !=
                                                    null
                                                ? Image.memory(
                                                    workList[index]['paint'],
                                                    width: 80.w,
                                                    height: 30.h,
                                                  )
                                                : Icon(
                                                    Icons.mode_edit,
                                                    color: Styles.BlueColor,
                                                    size: Styles.MiddleFont17,
                                                  ),
                                          ),
                                        )
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            );
                          },
                        ),
                        Container(
                          alignment: Alignment.centerLeft,
                          margin: EdgeInsets.fromLTRB(
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16),
                          child: Text(
                            '个人防护器材',
                            style: TextStyle(
                                color: Styles.TitleColor,
                                fontSize: Styles.Middle15Font),
                          ),
                        ),
                        Container(
                          alignment: Alignment.centerLeft,
                          child: Wrap(
                            children: personSafeListAll.map((e) {
                              return e['checkedTag'] == '1'
                                  ? Container(
                                      margin: EdgeInsets.fromLTRB(
                                          Styles.spacing8,
                                          0,
                                          0,
                                          Styles.spacing8),
                                      padding: EdgeInsets.fromLTRB(
                                          Styles.spacing8,
                                          Styles.spacing4,
                                          Styles.spacing8,
                                          Styles.spacing4),
                                      decoration: BoxDecoration(
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(12.r)),
                                          color: Styles.LightBlueColor2),
                                      child: Text(
                                        e['equipName'],
                                        style: TextStyle(
                                            color: Colors.white,
                                            fontSize: Styles.NormalFont13),
                                      ),
                                    )
                                  : SizedBox();
                            }).toList(),
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing8,
                              Styles.spacing16,
                              Styles.spacing8,
                              Styles.spacing16),
                          alignment: Alignment.centerLeft,
                          child: Text(
                            '气体检测',
                            style: TextStyle(
                                color: Styles.BlackColor,
                                fontSize: Styles.MainButtonTextFont,
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                        ...gasList.map((e) {
                          return Container(
                            decoration: BoxDecoration(
                                border: Border(
                                    bottom: BorderSide(
                                        color: Styles.LightSearch, width: 1))),
                            padding: EdgeInsets.fromLTRB(
                                Styles.spacing8,
                                Styles.spacing16,
                                Styles.spacing8,
                                Styles.spacing16),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  e['gasName'] ?? '--',
                                  style: TextStyle(
                                      color: Styles.TitleColor,
                                      fontSize: Styles.Middle15Font),
                                ),
                                Text(
                                  e['gasValue'] ?? '--',
                                  style: TextStyle(
                                      color: Styles.TitleColor,
                                      fontSize: Styles.Middle15Font),
                                )
                              ],
                            ),
                          );
                        }).toList(),
                        Container(
                          margin: EdgeInsets.fromLTRB(Styles.spacing8,
                              Styles.spacing16, Styles.spacing8, 0),
                          child: RichText(
                              text: TextSpan(children: [
                            // WidgetSpan(
                            //   child: Icon(
                            //     Icons.check_box,
                            //     color: Styles.BlueColor,
                            //     size: 16.0,
                            //   ),
                            // ),
                            TextSpan(
                              text:
                                  '我已做好上述准备工作，被告知并确认了工作中的危险性，我将同监护人一起确认现场安全状况，检查个人防护用品及器材，保证不在危险状况下参与工作。',
                              style: TextStyle(
                                  fontSize: Styles.NormalFont,
                                  color: Styles.TitleColor),
                            ),
                          ])),
                        ),
                        Container(
                          margin: EdgeInsets.fromLTRB(
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16),
                          alignment: Alignment.centerLeft,
                          color: Colors.white,
                          child: Row(
                            // mainAxisAlignment:
                            // MainAxisAlignment.spaceBetween,
                            children: [
                              Text.rich(TextSpan(children: [
                                TextSpan(
                                    text: '作业人签名：',
                                    style: TextStyle(
                                        fontSize: Styles.Middle15Font,
                                        color: Styles.TitleColor)),
                              ])),
                              signRecords.length > 0
                                  ? Image.network(
                                      "${GlobalConfig.baseUrl}fs/irest/file/mps_fileTransferHandler/image?id=${signRecords.first['signId']}&ZJQFSESSION=${GlobalConfig.session}",
                                      width: 80.w,
                                      height: 30.h,
                                    )
                                  : Container()
                            ],
                          ),
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: Container(
          padding: EdgeInsets.fromLTRB(
              Styles.spacing8, Styles.spacing8, Styles.spacing8, 10),
          child: Container(
            decoration: new BoxDecoration(
              //背景
              color: Styles.BlueColor,
              //设置四周圆角 角度
              borderRadius: BorderRadius.all(Radius.circular(12.0)),
            ),
            child: FlatButton(
              disabledColor: Styles.SelectColor,
              onPressed: () {
                FocusScope.of(context).requestFocus(new FocusNode());
                showDialog(
                    barrierDismissible: false,
                    context: this.context,
                    builder: (BuildContext context) {
                      return AlertDialog(
                        title: Text('注意'),
                        content: Text('确认提交吗？'),
                        actions: <Widget>[
                          new Container(
                            child: FlatButton(
                              child: new Text(
                                "取消",
                                style: TextStyle(color: Colors.black),
                              ),
                              onPressed: () {
                                Navigator.pop(context);
                              },
                            ),
                          ),
                          new Container(
                            child: FlatButton(
                              child: new Text(
                                "确定",
                                style: TextStyle(color: Colors.red),
                              ),
                              onPressed: () {
                                Navigator.pop(context);
                                this.addImage();
                                // this.submit();
                              },
                            ),
                          ),
                        ],
                      );
                    });
              },
              child: Container(
                height: Styles.MainButtonHeight,
                alignment: Alignment.center,
                child: Text(
                  '确定提交',
                  style: TextStyle(
                      fontSize: Styles.MainButtonTextFont, color: Colors.white),
                ),
              ),
            ),
          ),
        ));
  }
}
